// // 1.引入http模块
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  // 获取请求url的路径
  let { pathname } = new URL(req.url, 'http://127.0.0.1');

  let root = __dirname + '/page';
  // 拼接文件路径
  let filePath = root + pathname;
  // 读取文件fs 异步API
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.setHeader('content-type', 'text/html;charset=utf-8')
      res.statusCode = 500;
      res.end('文件读取失败');
      return
    }
    res.end(data);
  })
});

server.listen(9000, () => {
  console.log('服务器启动成功');
});